package com.zk.nakedfowl.barcodeMachineGrantManager.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.zk.nakedfowl.barcodeMachineGrantManager.dao.BarcodeMachineUserDao;
import com.zk.nakedfowl.barcodeMachineGrantManager.pojo.BarcodeMachineUser;
import com.zk.nakedfowl.common.util.IdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;


import com.zk.nakedfowl.barcodeMachineGrantManager.dao.MachineGrantDao;
import com.zk.nakedfowl.barcodeMachineGrantManager.pojo.MachineGrant;

/**
 * 服务层
 * 
 * @author Administrator
 */
@Service
public class MachineGrantService {

    @Autowired
    private MachineGrantDao machineGrantDao;
    @Autowired
    private BarcodeMachineUserDao barcodeMachineUserDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<MachineGrant> findAll() {
        return machineGrantDao.findAll();
    }

	
	/**
	 * 条件查询+分页
	 * @param whereMap
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<MachineGrant> findSearch(Map whereMap, int page, int size) {
		Specification<MachineGrant> specification = createSpecification(whereMap);
		PageRequest pageRequest =  PageRequest.of(page-1, size);
		return machineGrantDao.findAll(specification, pageRequest);
	}

	
	/**
	 * 条件查询
	 * @param whereMap
	 * @return
	 */
	public List<MachineGrant> findSearch(Map whereMap) {
		Specification<MachineGrant> specification = createSpecification(whereMap);
		return machineGrantDao.findAll(specification);
	}

	/**
	 * 根据ID查询实体
	 * @param id
	 * @return
	 */
	public MachineGrant findById(String id) {
		return machineGrantDao.findById(id).get();
	}

	/**
	 * 增加
	 * @param machineGrant
	 */
	public void add(MachineGrant machineGrant) {
		Calendar calendar= Calendar.getInstance();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
		String tmp = dateFormat.format(calendar.getTime());
		try{
			Date data = dateFormat.parse(tmp);
			machineGrant.setCreateDate(data);
		}catch (ParseException e){
			System.out.println(e);
		}
		machineGrant.setId( idWorker.nextId()+"" );
		machineGrantDao.save(machineGrant);

		//可用Rabbbit Mq实现异步通知
		//根据machineGrant 修改barcode_machine_user
		BarcodeMachineUser barcodeMachineUser = new BarcodeMachineUser();
		barcodeMachineUser.setId(idWorker.nextId() + "");
		barcodeMachineUser.setAdminId(machineGrant.getCreateBy());
		//barcodeMachineUser.setAdminIdCard(AdminDao.findById(AminId));
		barcodeMachineUser.setBarcodeMachineId(machineGrant.getBarcodeMachineId());
		barcodeMachineUser.setIsUpdate("1");
		//下面的跟adminId重合了，不需要
		//barcodeMachineUser.setMaintenanceId();
		//	barcodeMachineUser.setSlaughterHouseId();
		barcodeMachineUser.setUpdateDate(new Date());
		barcodeMachineUser.setUpdateVersion("1");
		barcodeMachineUser.setUserId(machineGrant.getReceivePerson());
		barcodeMachineUserDao.save(barcodeMachineUser);

	}


    /**
     * 修改
     *
     * @param machineGrant
     */
    public void update(MachineGrant machineGrant) {
        MachineGrant oldMachineGrant=machineGrantDao.findById(machineGrant.getId()).get();
        machineGrantDao.save(machineGrant);

        //Rabbbit
        //如果machineGrant中的userid和设备id两个修改了
        // 修改barcode_machine_user
        if (oldMachineGrant.getBarcodeMachineId().equals(machineGrant.getBarcodeMachineId())&&
        oldMachineGrant.getReceivePerson().equals(machineGrant.getReceivePerson()))
            return;

        BarcodeMachineUser barcodeMachineUser =  barcodeMachineUserDao.findByBarcodeMachineId(machineGrant.getBarcodeMachineId());
      if (barcodeMachineUser==null) {
          barcodeMachineUser.setId(idWorker.nextId() + "");
      }
          barcodeMachineUser.setAdminId(machineGrant.getCreateBy());
          //barcodeMachineUser.setAdminIdCard(AdminDao.findById(AminId));
          barcodeMachineUser.setBarcodeMachineId(machineGrant.getBarcodeMachineId());
          barcodeMachineUser.setIsUpdate("1");
          //下面的跟adminId重合了，不需要
          //barcodeMachineUser.setMaintenanceId();
          //	barcodeMachineUser.setSlaughterHouseId();
          barcodeMachineUser.setUpdateDate(new Date());
          barcodeMachineUser.setUpdateVersion(barcodeMachineUser.getUpdateVersion()+1);
          barcodeMachineUser.setUserId(machineGrant.getReceivePerson());
          barcodeMachineUserDao.save(barcodeMachineUser);


    }

	/**
	 * 删除
	 * @param id
	 */
	public void deleteById(String id) {
		machineGrantDao.deleteById(id);
	}

	/**
	 * 动态条件构建
	 * @param searchMap
	 * @return
	 */
	private Specification<MachineGrant> createSpecification(Map searchMap) {

        return new Specification<MachineGrant>() {

			@Override
			public Predicate toPredicate(Root<MachineGrant> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();
                // 
                if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
                	predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%"));
                }
                // 脚标机编号
                if (searchMap.get("barcodeMachineId")!=null && !"".equals(searchMap.get("barcodeMachineId"))) {
                	predicateList.add(cb.like(root.get("barcodeMachineId").as(String.class), "%"+(String)searchMap.get("barcodeMachineId")+"%"));
                }
                // 发放档口编号
                if (searchMap.get("stallsId")!=null && !"".equals(searchMap.get("stallsId"))) {
                	predicateList.add(cb.like(root.get("stallsId").as(String.class), "%"+(String)searchMap.get("stallsId")+"%"));
                }
                // 发放人员id
                if (searchMap.get("grantPerson")!=null && !"".equals(searchMap.get("grantPerson"))) {
                	predicateList.add(cb.like(root.get("grantPerson").as(String.class), "%"+(String)searchMap.get("grantPerson")+"%"));
                }
                // 领取人员id
                if (searchMap.get("receivePerson")!=null && !"".equals(searchMap.get("receivePerson"))) {
                	predicateList.add(cb.like(root.get("receivePerson").as(String.class), "%"+(String)searchMap.get("receivePerson")+"%"));
                }
                // 纸质协议编号
                if (searchMap.get("agreementNumber")!=null && !"".equals(searchMap.get("agreementNumber"))) {
                	predicateList.add(cb.like(root.get("agreementNumber").as(String.class), "%"+(String)searchMap.get("agreementNumber")+"%"));
                }
                // 创建者（发放人员）
                if (searchMap.get("createBy")!=null && !"".equals(searchMap.get("createBy"))) {
                	predicateList.add(cb.like(root.get("createBy").as(String.class), "%"+(String)searchMap.get("createBy")+"%"));
                }
				
				return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

			}
		};

	}

	public Object findByCreateBy(String createBy) {
	}
}
